﻿using CPPEI.Coolzon.Common;
using CPPEI.Coolzon.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CPPEI.Coolzon.Designer.Views
{
    /// <summary>
    /// Interaction logic for DataSourceWindow.xaml
    /// </summary>
    public partial class DataSourceWindow : Window
    {
        private List<ServiceProxy.DesignServiceRef.DataSource> _tmpDataSourceList;
        private System.Collections.ObjectModel.ObservableCollection<ServiceProxy.DesignServiceRef.DataSource> _dataSourceList;
        private string _tmpResult = string.Empty;
        private Guid _solutionGuid;
        public DataSourceWindow()
        {
            InitializeComponent();
        }

        private void _ctlAdd_Click(object sender, RoutedEventArgs e)
        {
            DataSourceDetailWindow window = new DataSourceDetailWindow();
            if (window.ShowDialog() == true)
            {
                _dataSourceList.Add(window.RetDataSource);
            }
        }

        private void _ctlRemove_Click(object sender, RoutedEventArgs e)
        {
            _tmpResult = string.Empty;
            if (_ctlDataSourceView.SelectedItems != null && _ctlDataSourceView.SelectedItems.Count > 0)
            {
                if (MessageBox.Show("是否确定删除?", "提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    if (_tmpDataSourceList == null)
                    {
                        _tmpDataSourceList = new List<ServiceProxy.DesignServiceRef.DataSource>();
                    }
                    else
                    {
                        _tmpDataSourceList.Clear();
                    }
                    foreach (var item in _ctlDataSourceView.SelectedItems)
                    {
                        _tmpDataSourceList.Add(item as ServiceProxy.DesignServiceRef.DataSource);
                    }
                    DeleteDataSource(_tmpDataSourceList[0]);
                    ProgressbarWindow.Instance.ShowProgress(true);
                }
            }
            else
            {
                CustomMessageBox.ShowWarning("请选择数据源");
            }
        }
        private void DeleteDataSource(ServiceProxy.DesignServiceRef.DataSource dataSource)
        {
            Event.NCL.NCLEventBus.Publish(new Event.NCL.BeginDeleteDataSourceEvent(UIContext.Current.Token, dataSource.Id));
            _tmpDataSourceList.Remove(dataSource);
        }
        [Subscribe]
        public void EndDeleteDataSource(Event.NCL.EndDeleteDataSourceEvent @event)
        {
            ServiceProxy.DesignServiceRef.DataSource tmpDataSource = _dataSourceList.First(a => a.Id == @event.DataSourceId);
            if (@event.State == Event.NCL.NCLEventState.Failure)
            {
                _tmpResult += string.Format("{0}:{1}{2}", tmpDataSource.Name, "删除失败", Environment.NewLine);
                Logger.ErrorToTag(Library.LogTAG, "删除数据源 {0} 失败,{1}", tmpDataSource.Name, @event.Error);
            }
            else if (@event.State == Event.NCL.NCLEventState.Finished)
            {
                Dispatcher.Invoke(() =>
                {
                    _dataSourceList.Remove(tmpDataSource);
                });
                _tmpResult += string.Format("{0}:{1}{2}", tmpDataSource.Name, "删除成功", Environment.NewLine);
                Logger.InfoToTag(Library.LogTAG, "删除数据源 {0} 成功", tmpDataSource.Name);
            }
            if (_tmpDataSourceList.Count > 0)
            {
                DeleteDataSource(_tmpDataSourceList[0]);
            }
            else
            {
                ProgressbarWindow.Instance.Complete();
                Dispatcher.Invoke(() =>
                {
                    CustomMessageBox.ShowInfo(_tmpResult, "删除结果");
                });
            }
        }

        private void _ctlEdit_Click(object sender, RoutedEventArgs e)
        {
            EditDataSource();
        }

        private void EditDataSource()
        {
            if (_ctlDataSourceView.SelectedItem != null)
            {
                DataSourceDetailWindow window = new DataSourceDetailWindow(_ctlDataSourceView.SelectedItem as ServiceProxy.DesignServiceRef.DataSource);
                if (window.ShowDialog() == true)
                {
                    _ctlDataSourceView.SelectedItem = window.RetDataSource;
                }
            }
            else
            {
                CustomMessageBox.ShowWarning("请选择数据源");
            }
        }

        private void _ctlPublish_Click(object sender, RoutedEventArgs e)
        {
            _tmpResult = string.Empty;
            if (_ctlDataSourceView.SelectedItems == null || _ctlDataSourceView.SelectedItems.Count <= 0)
            {
                Coolzon.UI.CustomMessageBox.ShowWarning("请选择数据源");
                return;
            }
            if (_tmpDataSourceList == null)
            {
                _tmpDataSourceList = new List<ServiceProxy.DesignServiceRef.DataSource>();
            }
            else
            {
                _tmpDataSourceList.Clear();
            }
            foreach (var item in _ctlDataSourceView.SelectedItems)
            {
                _tmpDataSourceList.Add(item as ServiceProxy.DesignServiceRef.DataSource);
            }
            if (_tmpDataSourceList != null && _tmpDataSourceList.Count > 0)
            {
                PublishDataSource(_tmpDataSourceList[0]);
            }
            ProgressbarWindow.Instance.ShowProgress(true);
        }
        private void _ctlPublishAll_Click(object sender, RoutedEventArgs e)
        {
            _tmpResult = string.Empty;
            if (_tmpDataSourceList == null)
            {
                _tmpDataSourceList = new List<ServiceProxy.DesignServiceRef.DataSource>();
            }
            else
            {
                _tmpDataSourceList.Clear();
            }
            if (_dataSourceList != null && _dataSourceList.Count > 0)
            {
                foreach (var item in _dataSourceList)
                {
                    _tmpDataSourceList.Add(item);
                }
                if (_tmpDataSourceList != null && _tmpDataSourceList.Count > 0)
                {
                    PublishDataSource(_tmpDataSourceList[0]);
                }
            }
            else
            {
                Coolzon.UI.CustomMessageBox.ShowWarning("没有数据源");
            }
        }

        private void PublishDataSource(ServiceProxy.DesignServiceRef.DataSource dataSource)
        {
            Event.NCL.NCLEventBus.Publish(new Event.NCL.BeginPublishDataSourceEvent(UIContext.Current.Token, dataSource.Id, _solutionGuid));
            _tmpDataSourceList.Remove(dataSource);
        }


        [Subscribe]
        public void EndPublishDataSource(Event.NCL.EndPublishDataSourceEvent @event)
        {
            ServiceProxy.DesignServiceRef.DataSource tmpDataSource = _dataSourceList.First(a => a.Id == @event.DataSourceId);
            if (@event.State == Event.NCL.NCLEventState.Failure)
            {
                _tmpResult += string.Format("{0}:{1}{2}", tmpDataSource.Name, "发布失败", Environment.NewLine);
                Logger.ErrorToTag(Library.LogTAG, "发布数据源 {0} 失败,{1}", tmpDataSource.Name, @event.Error);
            }
            else if (@event.State == Event.NCL.NCLEventState.Finished)
            {
                tmpDataSource.PublishedTime = DateTime.Now;
                _tmpResult += string.Format("{0}:{1}{2}", tmpDataSource.Name, "发布成功", Environment.NewLine);
                Logger.InfoToTag(Library.LogTAG, "发布数据源 {0} 成功", tmpDataSource.Name);
            }
            if (_tmpDataSourceList.Count > 0)
            {
                PublishDataSource(_tmpDataSourceList[0]);
            }
            else
            {
                ProgressbarWindow.Instance.Complete();
                Dispatcher.Invoke(() =>
                {
                    Coolzon.UI.CustomMessageBox.ShowInfo(_tmpResult, "发布结果");
                });
            }
        }

        private void ListViewItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            EditDataSource();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Event.NCL.NCLEventBus.Register(this);
            if (UIContext.Current.CurrentSolution == null)
            {
                _solutionGuid = Guid.Empty;
            }
            else
            {
                _solutionGuid = UIContext.Current.CurrentSolution.ID;
            }
            Event.NCL.NCLEventBus.Publish(new Event.NCL.BeginGetDataSourceListEvent(UIContext.Current.Token, _solutionGuid));
        }

        [Subscribe]
        public void EndGetDataSourceList(Event.NCL.EndGetDataSourceListEvent @event)
        {
            _dataSourceList = new System.Collections.ObjectModel.ObservableCollection<ServiceProxy.DesignServiceRef.DataSource>();
            if (@event.State == Event.NCL.NCLEventState.Failure)
            {
                Dispatcher.Invoke(() =>
                {
                    _ctlRetry.Visibility = Visibility.Visible;
                });
            }
            else if (@event.State == Event.NCL.NCLEventState.Finished)
            {
                if (@event.DataSources != null)
                {
                    foreach (var item in @event.DataSources)
                    {
                        _dataSourceList.Add(item);
                    }
                }
            }
            Dispatcher.Invoke(() =>
            {
                _ctlSPDataSource.IsEnabled = true;
                _ctlDataSourceView.ItemsSource = _dataSourceList;
            });
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Event.NCL.NCLEventBus.Unregister(this);
        }

        private void _ctlRetry_Click(object sender, RoutedEventArgs e)
        {
            Event.NCL.NCLEventBus.Publish(new Event.NCL.BeginGetDataSourceListEvent(UIContext.Current.Token, _solutionGuid));
            _ctlRetry.Visibility = Visibility.Collapsed;
            _ctlSPDataSource.IsEnabled = false;
        }

    }
}
